package com.github.pig.admin.controller.zhgl.community;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.controller.SysCommunityUserController;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.zhgl.building.CommunityBuildingTree;
import com.github.pig.admin.model.zhgl.community.CommunityInfo;
import com.github.pig.admin.service.sys.SysDeptService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.admin.service.zhgl.community.ICommunityInfoService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * @since 2018-06-04
 */
@Controller
@RequestMapping("/community")
public class CommunityController extends BaseController {
    @Autowired
    private ICommunityInfoService communityInfoService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysCommunityUserController sysCommunityUserController;








    /**
     * 通过部门id查询子部门下所有园区
     *
     * @param id
     * @return list
     */
    @GetMapping("/{id}")
    @ResponseBody
    public List<CommunityInfo> getCommunityInfos(@PathVariable Integer id){
        return communityInfoService.getCommunityInfos(id) ;
    }
    @RequestMapping("/upload")
    @ResponseBody
    public AjaxJson upload(ModelMap modelMap, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            try {
                List<CommunityInfo> list = ExcelImportUtil.importExcel(file.getInputStream(),CommunityInfo.class,params);
                if(list==null||list.size()==0){
                    j.setMsg("文件空内容。");
                    return j;
                }
                communityInfoService.insertBatch(list);
                j.setMsg("成功导入："+list.size()+"行");
            } catch (Exception e) {
                j.setSuccess(false);
                j.setMsg("文件导入失败！");
            }finally{
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }
    /**
     * 分页查询信息
     *
     * @param params 分页对象
     * @return 分页对象
     */
    @RequestMapping("/page")
    @ResponseBody
    public Page page(@RequestParam Map<String, Object> params, CommunityInfo communityInfoWhere) {
        EntityWrapper entityWrapper = new EntityWrapper<CommunityInfo>();
        //根据当前用户查询所在小区
        Page<CommunityInfo> page = new Page<CommunityInfo>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO userVO = sysUserService.findUserByUsername(currentUserName);
        List communityIdList = sysCommunityUserController.getCurrentUserCommunityId(userVO);
        // 判断是否是超级管理员"admin"
        if(CommonConstant.MANAGE_NAME.equalsIgnoreCase(currentUserName) == false){

            if (communityIdList != null && communityIdList.size() != 0){
                // 如果获取到的所属小区id集合不为空
                entityWrapper.in("id",communityIdList);
            }
        }
        //拼装条件
        initCondition(params,entityWrapper,communityInfoWhere);
        return communityInfoService.selectPage(page, entityWrapper);
    }

    private void initCondition(Map<String, Object> params, EntityWrapper entityWrapper, CommunityInfo communityBuildingWhere) {
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(communityBuildingWhere.getName())){
            entityWrapper.like("name",communityBuildingWhere.getName());
        }
    }

    /**
     * 添加
     * @param  communityInfo  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    public R<Boolean> add(@RequestBody CommunityInfo communityInfo) {
        communityInfo.setDelFlag(CommonConstant.STATUS_NORMAL);
        communityInfo.setCreateDate(new Date());
        return new R<>(communityInfoService.insert(communityInfo));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/doDel")
    @ResponseBody
    public AjaxJson delete( String id) {
        AjaxJson json=new AjaxJson();
        CommunityInfo communityBuilding = communityInfoService.selectById(id);
        communityBuilding.setDelFlag(CommonConstant.STATUS_DEL);
        boolean flag = communityInfoService.updateById(communityBuilding);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    @RequestMapping("/doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids){
        AjaxJson json=new AjaxJson();
        List<CommunityInfo> list = communityInfoService.selectBatchIds(Arrays.asList(ids.split(",")));
        for(CommunityInfo bean : list){
            bean.setDelFlag(CommonConstant.STATUS_DEL);
        }
        boolean flag = communityInfoService.updateBatchById(list);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    /**
     * 编辑
     * @param  communityInfo  实体
     * @return success/false
     */
    @RequestMapping("/doUpdate")
    @ResponseBody
    public R<Boolean> edit(@RequestBody CommunityInfo communityInfo) {
        return new R<>(communityInfoService.updateById(communityInfo));
    }

    /**
     * 获取部门列表
     */
    @RequestMapping("/deptList")
    @ResponseBody
    public List<SysDept> deptList(HttpServletRequest request) {
        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        return  sysDeptService.selectList(entityWrapper);
    }

    /**
     * 获取当前登陆人小区ID集合
     */
    @RequestMapping(params = "getCommunitysByCurrentUser")
    @ResponseBody
    public List<CommunityBuildingTree> getCommunitysByCurrentUser(HttpServletRequest request){
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        List<CommunityInfo> communitysByUserId = new ArrayList<>();
        List<CommunityBuildingTree> treeList = new ArrayList<>();
        if(CommonConstant.MANAGE_NAME.equalsIgnoreCase(currentUserName)){
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
            communitysByUserId = communityInfoService.selectList(entityWrapper);
        }else{
            //当前登陆人的企业，然后获取园区
            communitysByUserId = communityInfoService.getCommunitysByCurrentUser(currentUserName);
        }
        if(communitysByUserId==null||communitysByUserId.size()==0){
            List<SysDept> sysDepts = communityInfoService.getDeptsByCurrentUser(currentUserName);
            for(SysDept dept:sysDepts){
                CommunityInfo park = communityInfoService.selectById(dept.getParentId());
                CommunityBuildingTree treePark = new CommunityBuildingTree();
                treePark.setName(park.getName());
                treePark.setId(park.getId()==null?"":park.getId().toString());
                treePark.setType(CommonConstant.DEPTPROPERTY_PARK);
                treeList.add(treePark);
            }
        }else{
            for(CommunityInfo info : communitysByUserId){
                CommunityBuildingTree treeNode = new CommunityBuildingTree();
                treeNode.setName(info.getName());
                treeNode.setId(info.getId()==null?"":info.getId().toString());
                treeNode.setType(CommonConstant.DEPTPROPERTY_PARK);
                treeList.add(treeNode);
            }
        }
        return treeList;
    }

    /**
     * 根据部门id获取小区列表
     *
     * @param deptId  部门ID
     * @return 小区列表
     */
    @GetMapping("/communityList/{deptId}")
    @ResponseBody
    public List<CommunityInfo> communityInfoList(@PathVariable Integer deptId) {
        return communityInfoService.selectListByDeptId(deptId);

    }
    /**
     * 根据当前登录人用户id获取到用户所属小区
     *
     * @return 小区列表
     */
    @RequestMapping(params = "getCommunitysByUserId")
    @ResponseBody
    public List<CommunityInfo> getCommunitysByUserId(HttpServletRequest request){
        // 获取当前登录的用户
        Claims claims = getCurrentUserInfo();
        String currentUserName = (String) claims.get("user_name");
        UserVO userVO = sysUserService.findUserByUsername(currentUserName);
        List<CommunityInfo> communitysByUserId = new ArrayList<>();
        if(CommonConstant.MANAGE_NAME.equalsIgnoreCase(currentUserName)){
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
            entityWrapper.orderBy("sort",true);
            communitysByUserId = communityInfoService.selectList(entityWrapper);
        }else{
            communitysByUserId = communityInfoService.getCommunitysByUserId(userVO.getUserId());
        }
        return communitysByUserId;
    }

}
